import { MoreVert as MoreVertIcon } from '@mui/icons-material'
import GradeButton from './GradeButton'
import { ButtonConfig } from '@/store/constant'
import { ButtonType, GradeItem } from '@/types/common'
import { ElementType } from 'react'

interface Props {
  row: GradeItem
  refresh: () => void
}

const ITEM_HEIGHT = 20
const GradeActionButton = ({ row, refresh }: Props) => {
  const [anchorEl, setAnchorEl] = useState<null | Element>(null)
  const open = Boolean(anchorEl)
  const handleClick = (event: React.MouseEvent) => {
    setAnchorEl(event.currentTarget)
  }
  const handleClose = () => {
    setAnchorEl(null)
  }
  return (
    <>
      <IconButton aria-label="settings" onClick={handleClick}>
        <MoreVertIcon />
      </IconButton>
      <Menu
        id="long-menu"
        MenuListProps={{
          'aria-labelledby': 'long-button'
        }}
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        PaperProps={{
          style: {
            maxHeight: ITEM_HEIGHT * 4.5,
            width: '20ch'
          }
        }}
      >
        {entries(pick(ButtonConfig, ['edit', 'delete'])).map(
          ([type, btn]: [type: keyof ButtonType, btn: { label: string; icon: ElementType }]) => {
            return (
              <GradeButton
                key={type}
                type={type}
                refresh={refresh}
                row={row}
                renderTrigger={(props) => (
                  <MenuItem {...props}>
                    <ListItemIcon>
                      <btn.icon size="1.2rem" />
                    </ListItemIcon>
                    <Typography variant="inherit">{btn.label}</Typography>
                  </MenuItem>
                )}
              />
            )
          }
        )}
      </Menu>
    </>
  )
}

export default GradeActionButton
